import subprocess


class Adb(object):
    def __init__(self, adb_path):
        self._adb_path = adb_path

    def get_dir(self, path):
        if not path.endswith("/"):
            path = path + "/"
        cmd = '{} shell  ls -F {} | grep "/$"'.format(self._adb_path, path)
        # cmd = 'ls -F ./ | grep "/$"'.format(path)
        print(cmd)
        pipe = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE, universal_newlines=True)

        lines = pipe.stdout.readlines()
        errors = pipe.stderr.readlines()
        if not lines and not errors:
            return True, []
        if lines:
            results = [line[:-2] for line in lines]
            return True, results
        elif errors:
            return False, errors[0][:-1]
        else:
            return False, '执行命令,出现未知错误'

    def get_file(self, path):
        if not path.endswith("/"):
            path = path + "/"
        cmd = '{} shell ls -al {} | grep "^-"'.format(self._adb_path, path)
        # cmd = 'ls -al ./ | grep "^-"'.format(path)
        print(cmd)
        pipe = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE, universal_newlines=True)

        lines = pipe.stdout.readlines()
        errors = pipe.stderr.readlines()

        if not lines and not errors:
            return True, []
        if lines:
            results = [line.split(" ")[-1][:-1] for line in lines]
            return True, results
        elif errors:
            return False, errors[0][:-1]
        else:
            return False, '执行命令,出现未知错误'

    def download_file(self, src, dst):
        cmd = '{} pull {} {}'.format(self._adb_path, src, dst)
        print(cmd)
        pipe = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE, universal_newlines=True)

        errors = pipe.stderr.readlines()

        if not errors:
            return True, 'success'

        return False, errors[0][:-1]

    def upload_file(self, src_path, dst_dir):
        cmd = '{} push {} {}'.format(self._adb_path, src_path, dst_dir)
        print(cmd)
        pipe = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE, universal_newlines=True)

        errors = pipe.stderr.readlines()

        if not errors:
            return True, 'success'

        return False, errors[0][:-1]

    def delete_file(self, path):
        cmd = '{} shell rm -rf {}'.format(self._adb_path, path)
        print(cmd)
        pipe = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE, universal_newlines=True)

        errors = pipe.stderr.readlines()

        if not errors:
            return True, 'success'

        return False, errors[0][:-1]
